import { messages } from "share/common";
import React from "react";
import { connect } from "react-redux";
import Priority from "components/template/priority";
import Condition from "components/condition";
import { Button, Form, Checkbox, Switch, Spin, Radio, Select } from "antd";
import { message } from "antd/lib/index";
import ConsumerUtil from "../consumer-util";
import CreateContract from "../components/create-contract";
import NewConsumerServer from "../new-consumer-server";

const If = Condition.If;
const FormItem = Form.Item;
const { Option } = Select;
@Form.create()
class AlitripEditFrame extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      isNew: false,
      editData: {}, // 编辑数据
      loading: false,
      loadingCorpId: true,
      priDefalultValue: {},
      corpIdOptions: [
        {
          label: "1",
          value: "1",
        },
        {
          label: "2",
          value: "2",
        },
      ],
    };
    this.applicationTypeOpts = [
      //应用类型
      { label: messages("supplier-1.key80") /*机票*/, key: "withFlightSupplier" },
      { label: messages("supplier-1.key81") /*酒店*/, key: "withHotelSupplier" },
      { label: messages("supplier-1.key82") /*火车*/, key: "withTrainSupplier" },
      { label: messages("supplier-1.key83") /*用车*/, key: "withCarSupplier" },
    ];
    this.itineraryTypeOpts = [
      //行程可选类型
      { label: messages("supplier-1.key80") /*机票*/, key: "withFlightApproval" },
      { label: messages("supplier-1.key81") /*酒店*/, key: "withHotelApproval" },
      { label: messages("supplier-1.key82") /*火车*/, key: "withTrainApproval" },
      { label: messages("supplier-1.key83") /*用车*/, key: "withCarApproval" },
    ];
    this.terminalTypeOpts = [
      //终端可选类型
      { label: messages("supplier-1.key845") /*App端*/, key: "appBookButton" },
      { label: messages("supplier-1.key846") /*PC端*/, key: "pcBookButton" },
    ];
    this.versionOpts = [
      {
        label: messages("supplier-1.key887") /*H5版本*/,
        value: 2,
      },
      {
        label: messages("supplier-1.key888") /*钉钉版-超级报销*/,
        value: 1,
      },
    ];
  }

  componentWillMount() {
    const { params } = this.props;
    const initValue = ConsumerUtil.initPriorityDataForCompany(this.props);
    this.setState(
      {
        editData: params,
        isNew: !params.levelCode,
        priDefalultValue: initValue,
      },
      this.props.form.resetFields
    );
    this.refreshCorpIds();
  }

  onPriorityChange = (values) => {
    this.setState({
      priDefalultValue: values,
    });
  };

  // 签约 打开弹框
  signUp = () => {
    this.setState({
      modalVisible: true,
    });
  };

  // 保存签约信息
  saveSignInfo = (signInfo) => {
    NewConsumerServer(this)
      .createAlitripContract(signInfo)
      .then((res) => {
        if (res.data.code === 0) {
          window.open(res.data.url, "_blank");
          this.refreshCorpIds();
        } else {
          message.error(res.data.message);
        }
      });
  };

  // 单点阿里商旅后台
  goToAlitripManagerPage = () => {
    const { getFieldValue } = this.props.form;
    const corpId = getFieldValue("corpId");
    if (!corpId) return;
    NewConsumerServer(this)
      .getAlitripManagerUrl({ corpId })
      .then((res) => {
        if (res.data.code === 0) {
          window.open(res.data.url, "_blank");
          this.refreshCorpIds();
        } else {
          message.error(res.data.message);
        }
      });
  };

  // 加载corpId下拉列表
  refreshCorpIds = () => {
    const { tenant } = this.props;
    NewConsumerServer(this)
      .getAlitripCorpIdList(tenant.id)
      .then((res) => {
        if (res.data.contractList) {
          const corpIdOptions = res.data.contractList.map((item) => ({ label: item.corpId, value: item.corpId }));
          this.setState({
            corpIdOptions,
          });
        }
      });
  };

  modalOnCancel = () => {
    this.setState({
      modalVisible: false,
    });
  };

  modalOnOk = (signInfo) => {
    this.setState({
      modalVisible: false,
    });
    if (signInfo) {
      this.saveSignInfo({ ...signInfo, tenantId: this.props.tenant.id });
    } else {
      this.refreshCorpIds();
    }
  };

  // 保存提交
  onSubmitEdit = () => {
    const { tenant } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { priDefalultValue, isNew, editData } = this.state;
        const authData = JSON.parse(JSON.stringify(priDefalultValue));
        if (!authData || !authData.levelOrgId || !authData.levelOrgName) {
          message.error(messages("supplier-1.key185") /*请填写所属组织*/);
          return;
        }
        const pri = {
          ...authData,
          companyName: authData.levelOrgName,
          distLevelOrgName: authData.distLevelOrgName,
          companyOID: authData.companyOID,
          tenantName: tenant.name,
        };
        let upParams = Object.assign({}, values, pri);
        upParams.tenantId = this.props.tenant.id;
        if (!isNew) {
          upParams = Object.assign({}, editData, upParams);
        }
        NewConsumerServer(this)
          .saveAlitripConfig(upParams)
          .then((res) => {
            if (!res.data.passFlag && res.data.message) {
              message.error(res.data.message);
            } else {
              this.props.close(true);
              this.props.form.resetFields();
            }
          });
      }
    });
  };

  onCancelEdit = () => {
    this.props.close();
    this.props.form.resetFields();
  };

  // 渲染弹框
  modalRender = () => {
    const { modalVisible } = this.state;
    return <CreateContract visible={modalVisible} onOk={this.modalOnOk} onCancel={this.modalOnCancel} />;
  };

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { editData, loading, isNew, priDefalultValue, corpIdOptions, loadingCorpId } = this.state;
    const formLayout = {
      labelCol: { span: 6, offset: 1 },
      wrapperCol: { span: 14 },
    };
    const linkClass = ["link-tip", getFieldValue("corpId") ? "" : "disabled"].join(" ");
    return (
      <div className="edit-frame alitrip-edit-frame">
        {this.modalRender()}
        <Spin spinning={loading}>
          <Form className="new-form">
            <FormItem label={messages("common.column.status") /*状态*/} {...formLayout}>
              {getFieldDecorator("enabled", {
                initialValue: editData.enabled || false,
                valuePropName: "checked",
              })(<Switch onChange={this.isOpenServer} />)}
            </FormItem>
            <Priority
              top="COMPANY"
              formItemLayout={formLayout}
              disabledTop={!isNew}
              companyProps={{ disabled: !isNew, valueKey: "id" }}
              defaultValue={!isNew ? priDefalultValue : null}
              onChange={this.onPriorityChange}
            />
            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key189") /*服务商参数设置*/}</div>
            </h3>
            <FormItem style={{ display: "flex" }} label={messages("supplier-1.key889") /*开通版本*/} {...formLayout}>
              {getFieldDecorator(`version`, {
                initialValue: editData.version || 2,
              })(<Radio.Group disabled={!isNew} options={this.versionOpts} />)}
              <If value={getFieldValue("version") === 2}>
                <div className="tips">
                  <div className="tips-text">
                    <div>
                      {messages("supplier-1.key890") /*未完成签约的公司，请先点击*/}
                      <span className="link-tip" onClick={this.signUp}>
                        {messages("supplier-1.key891") /*立即签约*/}
                      </span>
                      {
                        messages(
                          "supplier-1.key892"
                        ) /*完成信息录入，通过专用链接跳转至阿里商旅签约平台，在页面内完成授权*/
                      }{" "}
                      <br />
                      {
                        messages(
                          "supplier-1.key893"
                        ) /*授权完成后，阿里商旅暂无授权返回结果，若配置未生效，请及时联系消费商组查询*/
                      }
                    </div>
                  </div>
                </div>
              </If>
            </FormItem>
            <If value={getFieldValue("version") === 2}>
              <FormItem
                style={{ display: "flex" }}
                label={messages("supplier-1.key894") /*签约企业ID*/}
                {...formLayout}
              >
                {getFieldDecorator(`corpId`, {
                  initialValue: editData.corpId,
                  trigger: "onSelect",
                  rules: [
                    {
                      required: getFieldValue("version") === 2,
                      message: messages("supplier-1.key193") /*必填*/,
                    },
                  ],
                })(
                  <Select disabled={!isNew} style={{ width: "66%" }} loading={loadingCorpId}>
                    {corpIdOptions.map((opt) => {
                      return (
                        <Option key={opt.value} value={opt.value}>
                          {opt.label}
                        </Option>
                      );
                    })}
                  </Select>
                )}
                <div className="tips">
                  <div className="tips-text">
                    <div>
                      <span className="tip-orange">
                        {messages("supplier-1.key895") /*签约企业ID选择保存后不能修改。*/}
                      </span>
                      {messages("supplier-1.key896") /*如需配置差旅标准，请点击*/}
                      <span className={linkClass} onClick={this.goToAlitripManagerPage}>
                        {messages("supplier-1.key897") /*阿里商旅后台*/}
                      </span>
                    </div>
                  </div>
                </div>
              </FormItem>
            </If>
            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key194") /*服务商应用类型设置*/}</div>
            </h3>
            <FormItem
              style={{ display: "flex", alignItems: "center" }}
              label={messages("supplier-1.key195") /*应用类型*/}
              {...formLayout}
            >
              {this.applicationTypeOpts.map(({ key, label }) => {
                return (
                  <div key={key} className="edit-flex-box">
                    {getFieldDecorator(`${key}`, {
                      initialValue: editData[`${key}`] || false,
                      valuePropName: "checked",
                    })(<Checkbox>{label}</Checkbox>)}
                  </div>
                );
              })}
            </FormItem>
            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key196") /*申请单相关设置*/}</div>
            </h3>
            <FormItem
              className="form-label-style"
              label={messages("supplier-1.key197") /*行程上可选该服务商*/}
              {...formLayout}
            >
              {this.itineraryTypeOpts.map(({ key, label }) => {
                return (
                  <div key={key} className="edit-flex-box">
                    {getFieldDecorator(`${key}`, {
                      initialValue: editData[`${key}`] || false,
                      valuePropName: "checked",
                    })(<Checkbox>{label}</Checkbox>)}
                  </div>
                );
              })}
            </FormItem>
          </Form>
        </Spin>
        <div className="affix-bottom">
          <Button type="primary" loading={loading} onClick={this.onSubmitEdit}>
            {messages("common.ok") /*确定*/}
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button onClick={this.onCancelEdit}>{messages("common.cancel") /*取消*/}</Button>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    company: state.login.company,
    language: state.main.language,
  };
}

AlitripEditFrame.getEditData = (record, data, index) => {
  return record;
};

export default connect(mapStateToProps)(AlitripEditFrame);
